const axios = require('axios');
const chalk = require('chalk')
const crypto = require('crypto');
const fs = require('fs');

const robotWebHookUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c4a4e8a3-461d-41c8-b4f6-2ff976746bc9'; // 正式链接
// const robotWebHookUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=68c5cfe9-739c-40e7-a819-bb9c42fdfb69'; // 测试链接

// md5加密
const md5 = (data) => {
	const md5 = crypto.createHash('md5');
	return md5.update(data).digest('hex');
};

// 发送文本信息
const sendText = (value) => {
	axios
		.post(robotWebHookUrl, {
			msgtype: 'text',
			text: {
				content: value,
				mentioned_list: ['@all'],
			},
		})
		.then((res) => {
			console.log('res', res.body);
		});
};

// 发送文章信息
const sendArticle = ({ title, name, imageUrl, version, time }) => {
	axios
		.post(robotWebHookUrl, {
			msgtype: 'template_card',
			template_card: {
				card_type: 'news_notice',
				source: {
					icon_url:
						'https://wework.qpic.cn/wwpic/252813_jOfDHtcISzuodLa_1629280209/0',
					desc: title,
					desc_color: 0,
				},
				main_title: {
					title: name,
					desc: '小程序预览二维码已生成',
				},
				card_image: {
					url: imageUrl,
				},
				horizontal_content_list: [
					{
						keyname: '小程序名称',
						value: name,
					},
					{
						keyname: '预览版本',
						value: version,
					},
					{
						keyname: '提交时间',
						value: time,
					},
				],
				card_action: {
					type: 1,
					url: 'https://open.weixin.qq.com/sns/getexpappinfo?appid=wx3cae17d148bb62b6&path=pages%2Flogin%2Flogin.html#wechat-redirect',
					appid: 'APPID',
					pagepath: 'PAGEPATH',
				},
			},
		})
		.then((res) => {
			console.log('res.data', res.data);
		});
};

// 发送markdown
const sendMarkdown = (value) => {
	console.log(chalk.cyan('发送Markdown信息'))
	return axios
		.post(robotWebHookUrl, {
			msgtype: 'markdown',
			markdown: {
				content: value,
				mentioned_list: ['@all'],
			},
		})
};

// 发送图片
const sendPicture = (path) => {
	console.log(chalk.cyan('发送二维码图片'))
	fs.readFile(path, (err, data) => {
		axios
			.post(robotWebHookUrl, {
				msgtype: 'image',
				image: {
					base64: data.toString('base64'),
					md5: md5(data),
				},
			})
			.then((res) => {
				console.log(chalk.greenBright('图片发送成功'));
				fs.unlinkSync(path)
			});
	});
};

module.exports = {
	sendText,
	sendArticle,
	sendPicture,
	sendMarkdown,
};
